﻿using System;
using System.Threading;
using l1cs.server.datatables;
using l1cs.server.model;
using l1cs.server.model.Instance;
using l1cs.server.templates;

namespace l1cs.server
{
    public class NpcChatTimeController
    {
        private static Logger _log = Logger.getLogger( typeof( NpcChatTimeController ).FullName );

        private static NpcChatTimeController _instance;

        public static NpcChatTimeController getInstance()
        {
            if ( _instance == null )
            {
                _instance = new NpcChatTimeController();
            }
            return _instance;
        }

        public void threadSub( Object state )
        {
            while ( true )
            {
                checkNpcChatTime(); // チャット開始時間をチェック
                Thread.Sleep( 60000 );
            }
        }

        private void checkNpcChatTime()
        {
            foreach ( L1NpcChat npcChat in NpcChatTable.getInstance().getAllGameTime() )
            {
                if ( isChatTime( npcChat.getGameTime() ) )
                {
                    int npcId = npcChat.getNpcId();
                    foreach ( L1Object obj in L1World.getInstance().getObject() )
                    {
                        if ( !( obj is L1NpcInstance ) )
                        {
                            continue;
                        }
                        L1NpcInstance npc = (L1NpcInstance)obj;
                        if ( npc.getNpcTemplate().get_npcId() == npcId )
                        {
                            npc.startChat( L1NpcInstance.CHAT_TIMING_GAME_TIME );
                        }
                    }
                }
            }
        }

        private bool isChatTime( int chatTime )
        {
            int nowTime = Convert.ToInt32( DateTime.Now.ToString( "HHmm" ) );
            return ( nowTime == chatTime );
        }
    }
}
